/*
 * Created on Jun 7, 2005
 *
 */
package com.erclab.internal.xpresso.security;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.log4j.Logger;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.ApplicationDataSource;
import com.erclab.internal.xpresso.dataAccess.Query;
import com.erclab.internal.xpresso.exceptions.DataSourceException;
import com.erclab.internal.xpresso.exceptions.DirectoryException;
import com.erclab.internal.xpresso.handlers.UserRolesHandler;

/**
 * @author Enrique Rodriguez.
 *
 */
public class IntranetMySqlDirectory implements UserDirectory{

	protected final String USER_QUERY = "SELECT UserName, Email, idUser, netId FROM app_users WHERE netId=?";
	protected final String ROLES_QUERY = "SELECT RoleName FROM app_userspermissions, app_securityroles WHERE " +
                " app_securityroles.IdRole=app_userspermissions.IdRole AND IdUser=?";
	protected final String INSERT_VISIT_LOG = "INSERT INTO visitlog (netId, VisitDate, UserName) values(?,NOW(),?)";

	private static final Logger log = Logger.getLogger(IntranetMySqlDirectory.class);
	
	public void loadUserBean(User user) throws DirectoryException {
		String netId = user.getNetId();
		if (netId == null){
			throw new DirectoryException("The user ID cannot be null");
		}
		user.setNetId(removeDomain(netId));				
		loadUser(user);

	}

	protected User loadUser(User user) throws DirectoryException {
		log.info("Loading information for user: " + user.getNetId());
		ApplicationDataSource ads = Settings.getRepository().getApplicationDataSource(Settings.getDirectoryIdDataSource());
		QueryRunner run = new QueryRunner((DataSource)ads.getTheDataSource());
		
		ResultSetHandler rsHandler = new BeanHandler(User.class);
		
		// Load the user information    	
		try {
			user = (User)run.query(USER_QUERY, user.getNetId(), rsHandler);
		}catch(SQLException ex){
			throw new DirectoryException("A problem ocurred loading user information: " + ex);			
		}
		
		if (user == null){
			return null;
		}
		
		rsHandler = new UserRolesHandler(user);
		// Load the user information    	
		try {
			user = (User)run.query(ROLES_QUERY, "" + user.getIdUser(), rsHandler);
		}catch(SQLException ex){
			throw new DirectoryException("A problem ocurred loading the user roles: " + ex);			
		}
		return user;
	}
	
	/**
	 * @param netId
	 * @return
	 */
	protected String removeDomain(String netId) {
		if (netId.indexOf((char)92) > 0){
			netId = netId.substring(netId.indexOf((char)92) + 1, netId.length());
		}
		return netId;
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.security.UserDirectory#addVisitEntry(com.erclab.internal.xpresso.security.User)
	 */
	public void addVisitEntry(User user) throws DirectoryException {
		ApplicationDataSource ads = Settings.getRepository().getApplicationDataSource(Settings.getDirectoryIdDataSource());
		Query q = new Query();
		q.setQuery(INSERT_VISIT_LOG);
		q.setValues(new String[]{user.getNetId(), user.getUserName()});
		try {
			ads.executeQuery(q);
		} catch (DataSourceException e) {
			throw new DirectoryException("A problem ocurred: " + e);
		}

	}

	public void addRoleToUser(User user, String roleName) throws DirectoryException {
		// TODO Add the passed role to the user
	}

}
